<?php
namespace Home\Controller;

class FlowController extends \Think\Controller {
    // 把商品添加到购物车
    public function add() {
        // 根据地址栏传递的goods_id,查询商品信息
        $goods = D('Goods');
        if(!$goods->find(I('get.goods_id'))) {
            $this->redirect('Home/Index/index');
        }
        // 实例化购物车类
        $cat = \Home\Tool\CartTool::getIns();
        // 将商品添加到购物车中
        $cat->add($goods->goods_id,$goods->goods_name,$goods->shop_price);
        // 跳转到购物车页面
        $this->redirect('Home/Flow/checkout');
    }

    //购物车展示页面,准备下单
    public function checkout() {
        $cat = \Home\Tool\CartTool::getIns();

        // 判断购物车页面传来的方法名(减数量)
        if(I('method') == 'deleteOne') {
            $cat->decr(I('goods_id'));
        }

        if(I('method') == 'add') {
            $cat->add(I('goods_id'));
        }

        if(I('method') == 'deleteAll') {
            $cat->del(I('goods_id'));
        }

        $this->assign('goods',$cat->items());
        $this->assign('money',$cat->calcMoney());
        $this->display();
    }

    // 正式下单
    public function done() {
        $cat = \Home\Tool\CartTool::getIns();

        $oi = M('ordinfo');
        $oi->create(); // 自动收取post中数据
        // 设置ordinfo表中post中没有的其他字段
        $oi->ord_sn = $ord_sn = date('Ymd') . mt_rand(1000,9999);
        // 若为0 则是匿名购买
        $oi->user_id = cookie('user_id')?cookie('user_id'):0;
        $oi->money = $cat->calcMoney();
        $oi->ordtime = time();

        if($ordinfo_id = $oi->add()) {
            $og = M('ordgoods');

            $data = array();
            // 然后用$cat这个购物车类的对象调用购物车$items
            // $items这个goods_id做键值的二维数组中的数据
            foreach($cat->items() as $k=>$v) {
            // items()是购物车中的一个列出购物车中所有商品的方法
                $row = array();
                $row['goods_id'] = $k;
                $row['goods_name'] = $v['goods_name'];
                $row['shop_price'] = $v['shop_price'];
                $row['goods_num'] = $v['num'];
                $row['ordinfo_id'] = $ordinfo_id;
                $data[] = $row;
            }




            if($og->addAll($data)) {
                $this->assign('ordinfo',$oi->find($ordinfo_id));
                $this->assign('money',$cat->calcMoney());


/*                // 在线支付
                $jdpay = new \Home\Pay\JdPay($ord_sn , $cat->calcMoney());
                $this->assign('form' , $jdpay->form());*/

//                $alipay = new \Home\Pay\AliPay();
//                $alipay -> alipay($_POST);


                // 清空购物车
                $cat->clear();
                $this->display();
            } else {
                echo 'error';
            }
        }
    }

    public function showCart() {
        $cat = \Home\Tool\CartTool::getIns();

        $this->assign('goods',$cat->items());
        $this->assign('money',$cat->calcMoney());

        $this->display();
    }
}


















?>